from rest_framework import serializers

from MirrorCore.models.Badge import Badge, ArticleBadge, EssayBadge



class BadgeSerializer(serializers.ModelSerializer):

    color = serializers.CharField(required=False,allow_blank=True,allow_null=True)
    icon = serializers.CharField(required=False, allow_blank=True, allow_null=True)

    is_active = serializers.BooleanField(allow_null=True,required=False)
    class Meta:
        model = Badge
        fields = ['id', 'name', 'color', 'icon', 'photo', 'brief','type','author','is_active']
        extra_kwargs = {
            'color': {'required': False},
            'creator': {'write_only':True}
        }

    def update(self, instance, validated_data):
        return super().update(instance, validated_data)


"""
    一个更通用的badge设计
"""


class BadgeListSerializer(serializers.ListSerializer):
    """
    badge衍生序列化 其下badge无重复自动增删更,
    遍历新旧双方，多 create , 少 delete ,
    """
    def update(self, instance, validated_data):

        badge_mapping = {abadge.badge: abadge for abadge in instance}
        # print("yuan ",badge_mapping)
        data_mapping = {item["badge"]: item for item in validated_data}
        # print("xian ",data_mapping)
        ret = []

        for badge_id, data in data_mapping.items():
            # print(badge_id)
            badge = badge_mapping.get(badge_id,None)
            # print("wangwang",badge)
            if badge is None:
                ret.append(self.child.create(data))
            else:
                ret.append(self.child.update(badge,data))

        for badge_id , badge in badge_mapping.items():
            if badge_id not in data_mapping:
                badge.delete()

        return ret


class ArticleBadgeSerializer(serializers.ModelSerializer):
    # badge = BadgeSerializer()

    class Meta:
        model = ArticleBadge
        fields = ['article', 'count', 'badge']
        extra_kwargs = {
            'article': {'write_only': True}
        }
        list_serializer_class= BadgeListSerializer

    def create(self, validated_data):
        return super().create(validated_data)


class EssayBadgeSerializer(serializers.ModelSerializer):
    # badge = BadgeSerializer()

    class Meta:
        model = EssayBadge
        fields = ['essay', 'count', 'badge']
        extra_kwargs = {
            'essay': {'write_only': True}
        }
        list_serializer_class= BadgeListSerializer

    def create(self, validated_data):
        return super().create(validated_data)





